package com.ekingstar.framework.service.impl;

import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.transform.Transformers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.ekingstar.framework.domain.OnlineUser;
import com.ekingstar.framework.domain.SystemLog;
import com.ekingstar.framework.domain.User;
import com.ekingstar.framework.security.UserUtil;
import com.ekingstar.framework.service.IOnlineUserService;
import com.ekingstar.framework.util.HibernateCallbackUtil;
import com.ekingstar.framework.util.Page;

public class OnlineUserServiceImpl implements IOnlineUserService{

	private static Logger log = LoggerFactory.getLogger(OnlineUserServiceImpl.class);
	private HibernateTemplate hibernateTemplate;
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	
	public void addUser(OnlineUser user) {
		List list = this.hibernateTemplate.find("from OnlineUser as a where a.userName = '"+user.getUserName()+"'");
		if(list==null||list.size() == 0){
			this.hibernateTemplate.save(user);
		}else{
			OnlineUser ou = (OnlineUser)list.get(0);
			SystemLog  sl = new SystemLog();
			sl.setIp(user.getIpAddress());
			sl.setTime(new Date());
			sl.setType(SystemLog.LogType.logout.name());
			sl.setModelName("系统管理");
			sl.setUserId(UserUtil.getCurrentUserId());
			sl.setDescription("用户在其它登陆被迫下线");
			this.hibernateTemplate.save(sl);
			this.hibernateTemplate.delete(ou);
			this.hibernateTemplate.save(user);
		}
	}

	public boolean deleteUser(User user) {
		List list = this.hibernateTemplate.find("from OnlineUser as a where a.userName = '"+user.getName()+"'");
		if(list.size() ==1){
			OnlineUser ou = (OnlineUser)list.get(0);
			this.hibernateTemplate.delete(ou);
			return true;
		}else{
			return false;
		}
	}

	public Page getOnlineUserPage(OnlineUser onlineuser, int pageNo,
			int pageSize) {
		StringBuffer sb = new StringBuffer("select a.TUser.name as userName, a.TUser.loginTimes as loginTimes, a.ipAddress as ipAddress, " +
				" a.loginTime as loginTime, a.sessionId as sessionId from OnlineUser a where a.state = '1' ");
		Map params = new HashMap();
		if (pageNo <= 0 ) pageNo = 1;
		if (onlineuser != null ){
			if (onlineuser.getUserName() != null && !onlineuser.getUserName().trim().equals("")){
				sb.append(" and a.userName like :userName");
				params.put("userName","%"+onlineuser.getUserName().trim()+"%");
			}
		}
		HibernateCallback action = HibernateCallbackUtil.getCallbackWithPage(sb, params, Transformers.aliasToBean(OnlineUser.class), pageNo, pageSize);
		Page page  = (Page)hibernateTemplate.execute(action);
		return page;
	}
	
	public String getOnlineUserStr() {
		String returnValue="";
		StringBuffer sb = new StringBuffer("select a.TUser.name as userName from OnlineUser a where a.state = '1' ");
		List<String> list=hibernateTemplate.find(sb.toString());
		for (int i=0;i<list.size();i++)
		{
			returnValue+=list.get(i);
			if(i!=list.size()-1)
			returnValue+=" "; 
		}
		
		return returnValue;
	}


	public boolean deleteAllData() {
		// TODO Auto-generated method stub
		//this.hibernateTemplate
		this.hibernateTemplate.execute(new HibernateCallback(){
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				// TODO Auto-generated method stub
				session.createQuery("delete from OnlineUser").executeUpdate();
				return true;
			}
		});
		return false;
	}

	@SuppressWarnings("unchecked")
	public OnlineUser getUseIdBySessionId(String sessionId) {
		List list = this.hibernateTemplate.find("from OnlineUser a where a.sessionId = '"+sessionId+"' ");
		if(list.size() == 0 )
			return null;
		else
			return (OnlineUser)list.get(0);
	}


	@SuppressWarnings("unchecked")
	public String getIpByCurrentUser(User user) {
		try {
			List list = this.hibernateTemplate.find("select a.ipAddress from OnlineUser a where a.TUser.id = '"+user.getId()+"'");
			if(list.size() == 0){
				return "0.0.0.0";
			}else{
				return list.get(0).toString();
			}
		} catch (Exception e) {
			//System.out.println("----: Session event listener threw exception");
			return "0.0.0.0";
		}
	}
}
